﻿#include "OpenPrjDialog.h"
#include "ui_OpenPrjDialog.h"
#include "stores/DataStroes.h"
#include "components/SingleInstanceApplication/SingleInstanceApplication.h"

#include <QFileDialog>
#include <QDir>
#include <QFile>
#include "components/FWidgets/FMessageBox/FMessageBox.h"
#include <QDebug>

OpenPrjDialog::OpenPrjDialog(QWidget *parent)
    : FDialog(parent)
    , ui(new Ui::OpenPrjDialog)
{
    ui->setupUi(this);
    setWindowTitle(tr("Open Project"));

    QStringList recent = DataStroes::instance()->tlvPrj()->recentProjects();
    for (auto& prj : recent) {
        ClosableListWidgetItem* item = new ClosableListWidgetItem(ui->lwRecent);
        item->setText(prj);
        if (!QFile(prj).exists()) {
            item->setToolTip(tr("Project file does not exist!"));
            item->setIcon(QApplication::style()->standardIcon(QStyle::SP_MessageBoxWarning));
        }
        ui->lwRecent->addItem(item);
    }

    connect(ui->lwRecent, &ClosableListWidget::itemCloseRequested, ui->lwRecent, &ClosableListWidget::closeItem);
}

OpenPrjDialog::~OpenPrjDialog()
{
    delete ui;
}

void OpenPrjDialog::openProject(const QString &prjPath)
{
    if (!prjPath.endsWith(TLVPRJ_EXT)) {
        FMessageBox::critical(this, tr("Error"), tr("Project file extension must be \".tlvprj\"!"));
        return;
    }
    if (!QFile(prjPath).exists()) {
        FMessageBox::critical(this, tr("Error"), tr("Project file does not exist!"));
        return;
    }
    DataStroes::instance()->tlvPrj()->open(prjPath);
    qApp->restart(QStringList() << prjPath);
    accept();
}

void OpenPrjDialog::on_lwRecent_itemClicked(ClosableListWidgetItem *item)
{
    ui->lePrjPath->setText(item->text());
}

void OpenPrjDialog::on_lwRecent_itemActivated(ClosableListWidgetItem *item)
{
    openProject(item->text());
}

void OpenPrjDialog::on_lwRecent_itemRemoved(const QString &text)
{
    DataStroes::instance()->tlvPrj()->removeFromRecent(text);
}

void OpenPrjDialog::on_btnBrowse_clicked()
{
    QString prjPath = QFileDialog::getOpenFileName(this, tr("Select Tlv Project file"), QDir::homePath(), tr("Tlv Project File (*%1)").arg(TLVPRJ_EXT));
    if (!prjPath.isEmpty()) {
        ui->lePrjPath->setText(prjPath);
    }
}


void OpenPrjDialog::on_btnConfirm_clicked()
{
    openProject(ui->lePrjPath->text());
}


void OpenPrjDialog::on_btnCancel_clicked()
{
    reject();
}

